const Koa = require('koa');
const Router = require('koa-router');
const Mongoose = require('mongoose');
var bodyParser = require('koa-bodyparser');
const passport = require('koa-passport')

// 实例化koa
const app = new Koa();
const router = new Router();
app.use(bodyParser());


// 路由 
router.get('/', async ctx => {
  ctx.body = {
    msg: 'hello koa'
  }
});

// 引入user.js
const users = require('./routes/api/user')
// 引入profile.js
const profile = require('./routes/api/profile')

// config
const db = require('./config/keys').mongoURL
// 连接数据库
Mongoose.connect(db, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log("mongodb connected ...");
}).catch((err) => {
  console.log(err);
})

app.use(passport.initialize())
app.use(passport.session())
// 回调 config 文件 passport.js
require('./config/passport')(passport)

// 配置路由地址 localhost:5000/api/users
router.use("/api/users", users)
router.use("/api/profile", profile)
// 配置路由
app.use(router.routes()).use(router.allowedMethods());

// 端口号
const port = process.env.PORT || 5000;

// 监听端口号
app.listen(port, () => {
  console.log(`server started on ${port}`);
})